//
//  WBCompostTextView+Extension.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/16.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit

extension WBComposeTextView {
    
    var emoticonText: String {
        
        var result = ""
        // 在指定范围遍历textView的富文本获取对应的表情描述和普通的字符串, 然后拼接发送后台
        self.attributedText.enumerateAttributes(in: NSMakeRange(0, self.attributedText.length), options: []) { (info, range, _) in
            
            // info: 富文本信息
            
            // range : 富文本对应的范围
            
            // 判断是否是图片表情
            if let attachment = info["NSAttachment"] as? WBEmoticonTextAttachment {
                
                let chs = attachment.emoticon!.chs!
                
                result += chs
                
            } else {
                // 普通字符串富文本
                let subAttrbutedStr = self.attributedText.attributedSubstring(from: range)
                // 获取富文本对应的字符串
                let text = subAttrbutedStr.string
                
                result += text
                
            }
        }
        
        return result
    }
    
    
    // 根据表情模型插入富文本或者emoji
    func insertEmoticon(emticon:WBEmoticon) {
        
        if emticon.type == "0" {
        
            let lastAttributedText = NSMutableAttributedString(attributedString: self.attributedText)
            
            let emoticonAttributeText = NSAttributedString.attributedStringWithEmoticon(emoticon: emticon, font: self.font!)
            
                       // 5. 设置富文本
            // 获得选中范围的富文本
            var range = self.selectedRange
            // 替换选中范围的富文本
            lastAttributedText.replaceCharacters(in: range, with: emoticonAttributeText)
            // 设置富文本的字体大小
            lastAttributedText.addAttributes([NSFontAttributeName:self.font!], range: NSMakeRange(0, lastAttributedText.length))
            
            self.attributedText = lastAttributedText
            
            range.location += 1
            range.length = 0
            
            self.selectedRange = range
            
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            
            self.delegate?.textViewDidChange?(self)
            
        } else {
            
            let emoji = (emticon.code! as NSString).emoji()
            
            self.insertText(emoji!)
            
        }
        
    }
    
    
}
